import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Drawer, Empty, Form, message, Space, Table, Timeline, Typography } from 'antd'
import { EditFormInline, EditFormVertical } from '@/components/CustomForm'
import { useFormsurvey, useNumberAdd } from '../useForm'
import { useForm } from 'antd/es/form/Form'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './index.less'
import {
  addScheduleInsertNumber,
  getProduceQty,
  getProduceSchedule,
  getPurchaseSkc,
  scheduleDelete,
  updateProduceSchedule,
  updateScheduleTime,
} from '@/api/purchase'
import { ITableDataNumber, ITableDataTime, PurchaseProduceQtyVO, PurchaseProduceScheduleVO } from '../types'
import { useNumberDel, useTimeColumn } from '../columns'
import PermissionButton from '@/components/PermissionButton'
import dayjs from 'dayjs'
const Index = (props: { detailInfo: Record<string, any> }) => {
  const [Formsurvey] = useForm()
  const [FormNumber] = useForm()
  const [planList, setplanList] = useState<PurchaseProduceScheduleVO[]>([])
  const [surveyList, setsurveyList] = useState<IDesListType>([
    {
      label: '预计车缝人数',
      key: 'personQty',
      content: '-',
    },
    { label: '预计日产量', key: 'dailyProduceQty', content: '-' },
  ])
  const [issurveyEdit, setissurveyEdit] = useState<boolean>(false)
  const [isnumberEdit, setisnumberEdit] = useState<boolean>(false)
  const [istimeEdit, setistimeEdit] = useState<boolean>(false)
  const [numberList, setnumberList] = useState<PurchaseProduceQtyVO[]>([])
  const [isDrawModalShow, setisDrawModalShow] = useState<boolean>(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [stylecolorOptions, setstylecolorOptions] = useState<IOptionItem[]>([])
  useEffect(() => {
    getPlanList()
    getNumberList()
  }, [])

  const getPlanList = async () => {
    const res = await getProduceSchedule({
      purchaseOrderCode: props.detailInfo.purchaseOrderCode,
    })
    const planList = res?.data || []
    setplanList(planList)
    handleDetailFactory(surveyList, planList[0] || {}, setsurveyList)
  }
  const getNumberList = async () => {
    const res = await getProduceQty<PurchaseProduceQtyVO>({ purchaseOrderCode: props.detailInfo.purchaseOrderCode })
    if (res.code === 200) {
      setnumberList(res?.data || [])
    }
  }
  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList?.map((item) => {
      if (typeof item.format === 'function') {
        return {
          ...item,
          content: item.format(targetInfo),
        }
      } else {
        return {
          ...item,
          content: targetInfo?.[item.key + ''] || '-',
        }
      }
    })
    set(res)
  }
  const onDel = async (info: PurchaseProduceQtyVO) => {
    const res = await scheduleDelete({ id: info.id })
    if (res.code === 200) {
      message.success('操作成功')
      getNumberList()
    }
  }
  const onDrawCancel = () => {
    setisDrawModalShow(false)
    FormNumber.resetFields()
  }
  const onConfirm = async (values: any) => {
    setispedding(true)
    const stylecolor = values.stylecolor.split('-')
    Reflect.deleteProperty(values, 'stylecolor')
    const paramsData = {
      ...values,
      purchaseOrderCode: props.detailInfo.purchaseOrderCode,
      reportDate: dayjs(values.reportDate).format('YYYY-MM-DD'),
      spuCode: stylecolor[0],
      colorDetailName: stylecolor[1],
    }
    const res = await addScheduleInsertNumber(paramsData).finally(() => {
      setispedding(false)
    })
    if (res.code === 200) {
      message.success('操作成功')
      onDrawCancel()
      getNumberList()
    }
  }
  const addNumber = async () => {
    setisDrawModalShow(true)
    const res = await getPurchaseSkc<{ spuCode: string; colorDetailName: string }>({
      purchaseOrderCode: props.detailInfo.purchaseOrderCode,
    })
    if (res.code === 200) {
      const stylecolorOptions =
        res?.data?.map((item) => {
          return {
            label: item.spuCode + '-' + item.colorDetailName,
            value: item.spuCode + '-' + item.colorDetailName,
          }
        }) || []
      setstylecolorOptions(stylecolorOptions)
    }
  }
  return (
    <DetailContainer className="schedule_page_wrap">
      <Descriptions
        title="生产概况"
        list={issurveyEdit ? [] : surveyList}
        extra={
          <Space>
            <PermissionButton
              permission="EditProgress"
              type="primary"
              onClick={async () => {
                if (issurveyEdit) {
                  const data = await Formsurvey.validateFields()
                  const filterData = Object.fromEntries(Object.entries(data)?.filter(([_, val]) => val)) as Record<
                    string,
                    any
                  >
                  if (Object.keys(filterData).length === 0) {
                    message.warning('更新内容不能为空！')
                    return
                  }
                  const res = await updateProduceSchedule({
                    ...filterData,
                    purchaseOrderCode: props.detailInfo.purchaseOrderCode,
                  })
                  if (res.code === 200) {
                    message.success('更新成功')
                    setissurveyEdit(false)
                    getPlanList()
                  }
                } else {
                  Formsurvey.setFieldsValue({
                    personQty: planList[0]?.personQty,
                    dailyProduceQty: planList[0]?.dailyProduceQty,
                  })
                  setissurveyEdit(true)
                }
              }}
            >
              {issurveyEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {issurveyEdit ? (
              <Button
                onClick={() => {
                  setissurveyEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline className="sep_forminline_style" editConfig={useFormsurvey()} form={Formsurvey} />
      </Descriptions>
      <Descriptions
        title="生产数量跟踪"
        extra={
          <Space>
            <PermissionButton permission="EditProgress" type="primary" onClick={addNumber}>
              新增
            </PermissionButton>
            <PermissionButton
              permission="EditProgress"
              type="primary"
              onClick={async () => {
                if (isnumberEdit) {
                  setisnumberEdit(false)
                } else {
                  setisnumberEdit(true)
                }
              }}
            >
              {isnumberEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {isnumberEdit ? (
              <Button
                onClick={() => {
                  setisnumberEdit(false)
                  getNumberList()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <div className="custom_table_style width_limit_wrap">
          <Table
            bordered
            columns={useNumberDel({ onDel, isEdit: isnumberEdit })}
            dataSource={numberList}
            scroll={{ x: 600, y: 400 }}
            pagination={false}
            rowKey={(rows) => rows.id}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          />
        </div>
      </Descriptions>
      <Descriptions
        title="生产时间跟踪"
        extra={
          <Space>
            <PermissionButton
              permission="EditProgress"
              type="primary"
              onClick={async () => {
                if (istimeEdit) {
                  const res = await updateScheduleTime(planList)
                  if (res.code === 200) {
                    message.success('操作成功')
                    setistimeEdit(false)
                    getPlanList()
                  }
                } else {
                  setistimeEdit(true)
                }
              }}
            >
              {istimeEdit ? '保存修改' : '编辑'}
            </PermissionButton>
            {istimeEdit ? (
              <Button
                onClick={() => {
                  setistimeEdit(false)
                  getPlanList()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <div className="custom_table_style" style={{ width: '100%' }}>
          <Table
            bordered
            columns={useTimeColumn({ isEdit: istimeEdit, planList, setplanList })}
            dataSource={planList}
            scroll={{ x: 'max-content', y: 400 }}
            pagination={false}
            rowKey={(rows) => rows.id}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          />
        </div>
      </Descriptions>
      <Drawer
        title="新增生产数量跟踪"
        open={isDrawModalShow}
        maskClosable
        onClose={onDrawCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onDrawCancel}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormNumber.validateFields().then((values) => onConfirm(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useNumberAdd({ stylecolorOptions })}
          form={FormNumber}
          initialValues={{ reportDate: dayjs() }}
        />
      </Drawer>
    </DetailContainer>
  )
}
export default Index
